package com.boot.security.server.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import cn.hutool.core.date.DateUtil;
import com.boot.security.server.dao.*;
import com.boot.security.server.dto.AjaxJsonVo;
import com.boot.security.server.dto.AppPaymentOrderDto;
import com.boot.security.server.hitapp.api.hitapi;
import com.boot.security.server.hitapp.controller.AliPayController;
import com.boot.security.server.model.*;
import com.boot.security.server.utils.AppConstants;
import com.boot.security.server.utils.DateUtils;
import com.boot.security.server.utils.PayType;
import com.boot.security.server.utils.R;
import com.jpay.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boot.security.server.page.table.PageTableRequest;
import com.boot.security.server.page.table.PageTableHandler;
import com.boot.security.server.page.table.PageTableResponse;
import com.boot.security.server.page.table.PageTableHandler.CountHandler;
import com.boot.security.server.page.table.PageTableHandler.ListHandler;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/appPaymentOrders")
public class AppPaymentOrderController {
    @Autowired
    private AppVisitPayDao appVisitPayDao;
    @Autowired
    private AppPaymentOrderDao appPaymentOrderDao;
    @Autowired
    private AppPaymentDetailDao appPaymentDetailDao;
    @Autowired
    private AppAccountDao appAccountDao;
    @Autowired
    private AppTradePaynoDao appTradePaynoDao;
    @Autowired
    private AliPayController aliPayController;

    @PostMapping
    @ApiOperation(value = "保存")
    @Transactional
    public R save(@RequestBody AppPaymentOrder appPaymentOrder) {
        if(appPaymentOrder.getCardno()==null||appPaymentOrder.getCardtype()==null){
            return new R(new RuntimeException("参数错误"));
        }
        AppAccount account=new AppAccount();
        account.setCardno(appPaymentOrder.getCardno().toString());
        account.setCardtype(appPaymentOrder.getCardtype());
        account = appAccountDao.getBylist(account);
        String paymentid=DateUtils.getTimestampID();

        appPaymentOrder.setTradeno(paymentid); //订单号
        appPaymentOrder.setPaymentid(paymentid);
        appPaymentOrder.setRecipetdate(DateUtil.date());
        appPaymentOrder.setHostcode(account.getHostCode()); //医院编码
        appPaymentOrder.setPatientid(account.getPatientid()==null?null:Integer.parseInt(account.getPatientid()));//就诊id
        appPaymentOrder.setTimes(account.getTimes());//就诊次数
        appPaymentOrder.setPatientname(account.getRealName()); //患者姓名
        appPaymentOrder.setIdcard(account.getIdCard()); //有效证件号码
        //保存缴费订单记录
        appPaymentOrderDao.save(appPaymentOrder);
        List<AppPaymentDetail> list=appPaymentOrder.getItemList();
        AtomicInteger sort = new AtomicInteger(1);
        /**
         * 保存缴费订单明细
         */
        list.forEach(d ->{
                d.setPaymentid(paymentid);
                d.setPaymentdetailid(String.valueOf(sort.getAndIncrement()));//序号
                d.setRecipeno(appPaymentOrder.getRecipeno()==null?"":appPaymentOrder.getRecipeno().toString());//处方号
                d.setTradeno(appPaymentOrder.getTradeno()==null?"":appPaymentOrder.getTradeno().toString());//订单号
                d.setGroupid(appPaymentOrder.getGroupid()==null?"":appPaymentOrder.getGroupid().toString());//处方组号
                d.setRecipettype(appPaymentOrder.getRecipettype());
                d.setRecipetdate(DateUtil.now());
                d.setHostcode(appPaymentOrder.getHostcode());
                d.setPatientid(appPaymentOrder.getPatientid()==null?"":appPaymentOrder.getPatientid().toString());
                d.setTimes(appPaymentOrder.getTimes()==null?"":appPaymentOrder.getTimes().toString());
                appPaymentDetailDao.save(d) ;
        });
        return new R<AppPaymentOrder>(appPaymentOrder,"成功");
    }

    /**
     * 生成缴费记录、支付记录，统一下单生成支付二维码
     * @param param
     * @return
     */
    @PostMapping("/pay")
    @ApiOperation(value = "订单支付")
    @Transactional
    public R pay(@RequestBody Map<String,String> param) {

        if(param.get("tradeno")==null||param.get("payType")==null){
            return new R(new RuntimeException("支付失败，缺少参数"));
        }
        String tradeno=param.get("tradeno");
        String payType=param.get("payType");
        AppPaymentOrder order=new AppPaymentOrder();
        order.setTradeno(tradeno);
        order=appPaymentOrderDao.getBylist(order);
        if(order==null){
            return new R(new RuntimeException("订单信息不存在"));
        }
        if(AppConstants.ORDER_STATUS_SUCCESS.equals(order.getPaystaus())){
            return new R(new RuntimeException("该笔订单信息已经缴费"));
        }
        AppAccount account=new AppAccount();
        account.setCardno(order.getCardno().toString());
        account.setCardtype(order.getCardtype());
        account = appAccountDao.getBylist(account);
        //生成缴费记录
        AppVisitPay appVisitPay=new AppVisitPay(order,account);
        appVisitPayDao.save(appVisitPay);
        //生成支付记录
        AppTradePayno payno=new AppTradePayno(order,account);
        payno.setPaytype(payType); //支付类型
        payno.setChequtype(payType); //缴费类型
        //调用三方支付统一下单
        AjaxJsonVo vo=null;
        if(PayType.Al.getType().equals(payType)){//支付宝
            vo=aliPayController.tradePrecreatePay(payno);
        }else if(PayType.WX.getType().equals(payType)){//微信
            hitapi hitapi=new hitapi();
            vo=hitapi.wxpaydd(payno,payType);
        }else{
            return new R(new RuntimeException("不支持的支付类型"));
        }
        if(vo.isSuccess()){
            appTradePaynoDao.save(payno);
            Map<String, String> returnMap=(Map<String, String>) vo.getObj();
            returnMap.put("payAmount",payno.getTotalamount());
            return new R(returnMap,"成功");
        }else{
            return new R(new RuntimeException("支付失败，"+vo.getMsg()));
        }

    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id获取")
    public AppPaymentOrder get(@PathVariable Long id) {
        return appPaymentOrderDao.getById(id);
    }

    @PutMapping
    @ApiOperation(value = "修改")
    public AppPaymentOrder update(@RequestBody AppPaymentOrder appPaymentOrder) {
        appPaymentOrderDao.update(appPaymentOrder);

        return appPaymentOrder;
    }

    @GetMapping
    @ApiOperation(value = "列表")
    public PageTableResponse list(PageTableRequest request) {
        return new PageTableHandler(new CountHandler() {

            @Override
            public int count(PageTableRequest request) {
                return appPaymentOrderDao.count(request.getParams());
            }
        }, new ListHandler() {

            @Override
            public List<AppPaymentOrder> list(PageTableRequest request) {
                return appPaymentOrderDao.list(request.getParams(), request.getOffset(), request.getLimit());
            }
        }).handle(request);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除")
    public void delete(@PathVariable Long id) {
        appPaymentOrderDao.delete(id);
    }
    @PostMapping("/find")
    @ApiOperation(value = "查询")
    public R find(@RequestBody AppPaymentOrder appPaymentOrder){
        AppPaymentOrder getBylist = appPaymentOrderDao.getBylist(appPaymentOrder);
        if (getBylist == null) {
            return new R("", "", 100);
        }
        return new R(getBylist);
    }

    /**
     * 查询
     * @param  appPaymentOrderDto
     * @return R
     */
    @PostMapping("/findlist")
    public R findinfo(@RequestBody AppPaymentOrderDto appPaymentOrderDto){

        Map<String,Object> map = new HashMap<String,Object  >();
        //    map=entityToMap(appAccount);
        // 支付中 100   200 支付失败  0支付成功  appApponitDao.getBylist("")
        return new R<>( );

        //    return new R<>(  bxbFbqksDao.getById(bxbFbqks.getId()));
    }
}
